//
//  DetailProduct.m
//  VivaModa
//
//  Created by Sergey on 2/18/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "DetailProduct.h"
#import "product_description_cell.h"


@interface DetailProduct (){
    NSMutableArray *products;
    NSMutableArray *array_images;
}

@end

@implementation DetailProduct
@synthesize tableView;
@synthesize price;
@synthesize name_product;
@synthesize image_default;
@synthesize name_product_label;
@synthesize price_label;
@synthesize name_image;
@synthesize short_description;
@synthesize infoData;
@synthesize id_product;
@synthesize articul;
@synthesize count_products;
@synthesize needReload;
@synthesize fromSearch;
@synthesize name_categoria;
@synthesize price_const;
@synthesize articul_const;
@synthesize rub_const;
@synthesize button_buy;
@synthesize button_support;


NSDictionary *dict_data_product;
NSString *articul_text;
NSString *imagesToSaveDB;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
    barButton.title = @"Назад";
     self.navigationItem.backBarButtonItem = barButton;
    self.view.backgroundColor = [Singleton sharedMySingleton].backgroundTableView;
   
    [self addCustomBackButton];
    [self.name_categoria setFont:[UIFont fontWithName:@"Century Gothic" size:12.0]];
    [self.name_product_label setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:27]];
    
    
    [self.articul_const setFont:[UIFont fontWithName:@"Century Gothic" size:12.0]];
    [self.price_const setFont:[UIFont fontWithName:@"Century Gothic" size:12.0]];
    [self.rub_const setFont:[UIFont fontWithName:@"Century Gothic" size:12.0]];
    
    [self.price_label setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:17]];
    [self.articul setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:13]];
    
    [self.button_buy setTitle:@"Купить" forState:UIControlStateNormal];
    
    [self.button_buy setBackgroundImage:[UIImage imageNamed:@"buy_bg_btn"] forState:UIControlStateNormal];
    [self.button_buy setBackgroundImage:[UIImage imageNamed:@"buy_bg_btn_sel"] forState:UIControlStateHighlighted];
    
    
    [self.button_support setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.button_support setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
    
    //[self.button_support setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateHighlighted];
    
    // Do any additional setup after loading the view from its nib.
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (needReload) {
        needReload = NO;
        [self initArray];
        [self parseData];
        [self fiell_data];
        self.count_products.text = @"1";
        //NSLog(@"id product = %i",self.id_product);
    }

    
}





- (void)fiell_data{
    NSString *text_name = @"";
    if ([self.name_product length]>0) {
        NSArray *array_w = [self.name_product componentsSeparatedByString:@" "];
        if ([array_w count]>1 && (![[[array_w objectAtIndex:0] substringToIndex:1] isEqualToString:@"\""]) ) {
            self.name_categoria.text = [array_w objectAtIndex:0];
            for (int i = 1; i<[array_w count]; i++) {
                text_name = [NSString stringWithFormat:@"%@ %@",text_name,[array_w objectAtIndex:i]];
            }
            self.name_product_label.text = text_name;
        }else{
            self.name_product_label.text = self.name_product;
        }
    }
    
    
    
    
    
    
    
    
    self.price_label.text = [NSString stringWithFormat:@"%i",self.price];
    
    articul_text = [NSString stringWithFormat:@"%@",[dict_data_product objectForKey:@"products_model"]];
    
    self.articul.text = articul_text;
    
    [self.image_default setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/images/product_images/info_images/%@",self.name_image]]
                     placeholderImage:[UIImage imageNamed:@"radio_btn_active"]];
    
    self.image_default.layer.masksToBounds = YES;
    [self.image_default.layer setCornerRadius:12];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"product_description_cell";
    product_description_cell *cell = nil;
    cell = (product_description_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"product_description_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[product_description_cell class]])
            {
                cell = (product_description_cell *)currentObject;
                break;
            }
        }
    }

    UIFont *cellFont;
    switch (indexPath.row) {
        case 0:{//brend
            cellFont =  [UIFont fontWithName:@"Verdana" size:12];
            cell.text_data.text = [dict_data_product objectForKey:@"manufacturers_name"];
            cell.text_data.textColor = [UIColor colorWithRed:229.0/255 green:43.0/255 blue:106.0/255 alpha:1];
            [cell.text_data setFont:[UIFont fontWithName:@"Verdana" size:12]];
            break;}
        case 1:{/// short descriptin
            cellFont =  [UIFont fontWithName:@"Verdana-Bold" size:12];
            
            cell.text_data.textColor = [UIColor colorWithRed:39.0/255 green:38.0/255 blue:32.0/255 alpha:1];
            [cell.text_data setFont:[UIFont fontWithName:@"Verdana-Bold" size:15]];
            
            cell.text_data.text = self.short_description;
            break;}
        case 2:{// description
            cellFont =  [UIFont fontWithName:@"Verdana" size:15];
            cell.text_data.textColor = [UIColor colorWithRed:39.0/255 green:38.0/255 blue:32.0/255 alpha:1];
            [cell.text_data setFont:[UIFont fontWithName:@"Verdana" size:15]];
            cell.text_data.text = [dict_data_product objectForKey:@"products_description"];
            break;}
        case 3:{////size ornament
            cellFont =  [UIFont systemFontOfSize:15.0];
            cell.text_data.text = @"";
            break;}
        default:
            return 0;
            break;
    }
    cell.text_data.font = cellFont;
    return cell;
}



#pragma mark - Table view delegate


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UIFont *cellFont;
    switch (indexPath.row) {
        case 0:{//brend
            cellFont =  [UIFont fontWithName:@"Verdana" size:12];
            return [self getHeighFromText:[dict_data_product objectForKey:@"manufacturers_name"] andFont:cellFont];
            break;}
        case 1:{/// short descriptin
            cellFont =  [UIFont fontWithName:@"Verdana-Bold" size:12];
            return [self getHeighFromText:self.short_description andFont:cellFont];
            break;}
        case 2:{// description
            cellFont =  [UIFont fontWithName:@"Verdana" size:15];
            return [self getHeighFromText:[dict_data_product objectForKey:@"products_description"] andFont:cellFont];
            break;}
        case 3:{////size ornament
            cellFont =  [UIFont fontWithName:@"Verdana" size:15];
            return [self getHeighFromText:@"" andFont:cellFont];
            break;}
        default:
            return 0;
            break;
    }
    
}



- (float)getHeighFromText:(NSString*)text andFont:(UIFont*)font{
     ///[UIFont fontWithName:@"Helvetica-Bold" size:20.0f];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    
    CGSize labelSize = [text sizeWithFont:font
                            constrainedToSize:constraintSize
                                lineBreakMode:UILineBreakModeWordWrap];
    if ([text length]<1) {
        return 0;
    }
    
    return labelSize.height + 20.0f;
}









#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark



-(void)parseData{
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/mobile/get_product.php?id=%i",self.id_product]];
    
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection) {
        self.infoData = [NSMutableData data];
    }
}




- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [infoData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    //NSString *result = [[NSString alloc] initWithData:infoData encoding:NSUTF8StringEncoding];
    //NSLog(@"result = %@", result);
    [self parseJSON:infoData];
    // [self removeActivityView];
    
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data{

    NSError* error;
    
    NSDictionary* json = [NSJSONSerialization
                          
                          JSONObjectWithData:data
                          
                          options:kNilOptions
                          
                          error:&error];
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    
    
    
    NSDictionary* images = [json objectForKey:@"images"];
    
    //NSLog(@"%@",images);
    
     
    NSDictionary * dictdata = [json objectForKey:@"message"];
    
    NSArray * array_img = [json objectForKey:@"images"];
    
    //NSLog(@"arrayarray  = %@",dictdata);
    
    
    if ([requestResultAutorization integerValue]==1) {
        
        dict_data_product = dictdata;
     
        [array_images addObject:self.name_image];
        imagesToSaveDB = [NSString stringWithFormat:@"%@",self.name_image];
        
        
        for (int i=0; i< [array_img count];i++) {
            [array_images addObject:[array_img objectAtIndex:i]];
            imagesToSaveDB = [NSString stringWithFormat:@"%@|%@",imagesToSaveDB,[array_img objectAtIndex:i]];
        }
        //NSLog(@"array_images = %@",array_images);
        
        
        
        
        [SQLiteAccess deleteWithSQL:[NSString stringWithFormat:@"DELETE FROM ProductDetail WHERE product_id=%i",self.id_product]];
        [SQLiteAccess insertWithSQL:[NSString stringWithFormat:@"INSERT INTO ProductDetail(product_id,products_description,products_model,manufacturers_name,images) VALUES(%i,'%@','%@','%@','%@')",self.id_product,[dict_data_product objectForKey:@"products_description"],[dict_data_product objectForKey:@"products_model"],[dict_data_product objectForKey:@"manufacturers_name"],imagesToSaveDB ]];
        
        
    }else{
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Уведомление" message:@"Ошибка синхронизации" delegate:nil cancelButtonTitle:@"Закрыть" otherButtonTitles:nil];
        [alert show];
    }
    
        
    [self.tableView reloadData];
    [self fiell_data];
    [self removeActivityView];
    
}






-(void)getLastSavedData{
    NSArray *savedData = [SQLiteAccess selectManyRowsWithSQL:[NSString stringWithFormat:@"SELECT * FROM ProductDetail WHERE product_id=%i",self.id_product]];

    
    if ([savedData count]>0) {
        NSArray *arrayImag = [[[savedData objectAtIndex:0] objectForKey:@"images"] componentsSeparatedByString:@"|"] ;
        [array_images removeAllObjects];
        array_images = [NSMutableArray arrayWithArray:arrayImag];
        
        //NSLog(@"CUSTOM array_images = %@",array_images);
        
        dict_data_product = [savedData objectAtIndex:0];
        [self.tableView reloadData];
        [self fiell_data];
    }
    
   
}





- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [self getLastSavedData];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseData) withObject:nil afterDelay:1.0];
    }];
    [alert show];
}






-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}











-(IBAction)changeCountProducts:(id)sender{
    int current_count_pr = [self.count_products.text integerValue];
    
    switch ([sender tag]) {
        case 1:{
            if (current_count_pr>1) {
                current_count_pr--;
                self.count_products.text = [NSString stringWithFormat:@"%i",current_count_pr];
            }
            
            break;}
        case 2:{
            if (current_count_pr<100) {
                current_count_pr++;
                self.count_products.text = [NSString stringWithFormat:@"%i",current_count_pr];
            }

            break;}
        default:
            break;
    }
}



-(void)initArray{
    [products removeAllObjects];
    products = [[NSMutableArray alloc] initWithCapacity:1];
    
    [array_images removeAllObjects];
    array_images = [[NSMutableArray alloc] initWithCapacity:1];
}



-(IBAction)openAllImages:(id)sender{
    NSMutableArray *array_int_imges = [[NSMutableArray alloc] initWithCapacity:1];
    
    for (int i =0; i< [array_images count]; i++) {
        MyPhoto *photo = [[MyPhoto alloc] initWithImageURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://moda.viva-viva.ru/images/product_images/original_images/%@",[array_images objectAtIndex:i] ]] name:@""];
        [array_int_imges addObject:photo];
    }
    
    
    if ([array_int_imges count]>0) {
        MyPhotoSource *source = [[MyPhotoSource alloc] initWithPhotos:array_int_imges];
        
        EGOPhotoViewController *photoController = [[EGOPhotoViewController alloc] initWithPhotoSource:source];
        
        
        [self.navigationController pushViewController:photoController animated:YES];
    }
}


-(IBAction)addToBasket:(id)sender{
    [self insertProductToBasketTable];
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Товар успешно добавлен в корзину."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
    }];
    
    [alert show];
}


- (void)insertProductToBasketTable{
    NSArray *basketData = [SQLiteAccess selectManyRowsWithSQL:[NSString stringWithFormat:@"SELECT count FROM Basket WHERE id_product=%i",self.id_product]];
    int current_count = [self.count_products.text integerValue];
    
    if ([basketData count]>0) {
        int old_count = [[[basketData objectAtIndex:0] objectForKey:@"count"] integerValue];
        [SQLiteAccess updateWithSQL:[NSString stringWithFormat:@"UPDATE Basket SET count=%i WHERE id_product=%i;",current_count+old_count,self.id_product]];
    }else{
        [SQLiteAccess insertWithSQL:[NSString stringWithFormat:@"INSERT INTO Basket"
                                     "(count,id_product,name_product,short_description,price, small_image,products_quantity,products_description, products_model,manufacturers_name,images)"
                                     "VALUES('%i','%i','%@','%@','%i','%@','%@','%@','%@','%@','%@');",current_count,self.id_product,self.name_product,self.short_description,self.price,self.name_image,self.products_quantity,[dict_data_product objectForKey:@"products_description"],[dict_data_product objectForKey:@"products_model"],[dict_data_product objectForKey:@"manufacturers_name"],imagesToSaveDB]];
    }
    
    [[Singleton sharedMySingleton] setBadge];
}





-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65, 29)];
    //[backButton setImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Назад" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}

-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}


-(IBAction)supportRequest:(id)sender{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController* mailController = [[MFMailComposeViewController alloc] init];
        [mailController.navigationBar setBarStyle:UIBarStyleBlack];
        mailController.mailComposeDelegate = self;
        [mailController setToRecipients:[NSArray arrayWithObjects:@"office@viva-viva.ru",nil]];
        [mailController setSubject:[NSString stringWithFormat:@"Вопрос по товару %@",self.name_product]];
        //[[[[mailController viewControllers] lastObject] navigationItem] setTitle:@"Свяжитесь с нами"];
        
        [mailController setMessageBody:[NSString stringWithFormat:@"Здравствуйте, \n\n\n\nОтправлено из приложения для iOS\n"]  isHTML:NO];
        
        
        [self presentModalViewController:mailController animated:YES];
        //[[[[mailController viewControllers] lastObject] navigationItem] setTitle:@"Свяжитесь с нами"];
    }
    else {
        NSLog(@"%@", @"Sorry, you need to setup mail first!");
    }
}



- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error;
{
    [self dismissModalViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
